package com.tsvetanv.data.binding.model.property.editors.custom;

import java.beans.PropertyEditorSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

public class PhoneNumberEditor extends PropertyEditorSupport {

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (!StringUtils.hasText(text)) {
			throw new IllegalArgumentException("text must not be empty or null");
		}

		Pattern pattern = Pattern.compile("^\\((\\d{3})\\) (\\d{3})-(\\d{4})$");
		Matcher matcher = pattern.matcher(text);

		if (matcher.matches()) {
			PhoneNumber phone = new PhoneNumber();
			phone.setAreaCode(matcher.group(1));
			phone.setPrefix(matcher.group(2));
			phone.setSuffix(matcher.group(3));

			setValue(phone);
		} else {
			throw new IllegalArgumentException(text
					+ " does not match the pattern " + pattern);
		}
	}

	@Override
	public String getAsText() {
		return getValue().toString();
	}
}
